<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import {
  ElCard,
  ElDatePicker,
  ElSelect,
  ElButton,
  ElRow,
  ElCol,
  ElStatistic
} from 'element-plus'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { getOrdersStatistics } from '@/api/order'

// 状态数据
const loading = ref(false)
const statisticsData = ref(null)

// 获取明天日期的函数
const getTomorrowDate = () => {
  const date = new Date()
  date.setDate(date.getDate() + 1) // 加一天
  return date.toISOString().split('T')[0] // 格式: YYYY-MM-DD
}
// 查询参数
const queryParams = reactive({
  startDate: '1970-01-01',
  endDate: getTomorrowDate(),
  type: 'day'
})

// 统计类型选项
const typeOptions = [
  { value: 'day', label: '日统计' },
  { value: 'week', label: '周统计' },
  { value: 'month', label: '月统计' },
  { value: 'year', label: '年统计' }
]

// 获取统计数据
const getStatisticsData = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams(queryParams)
    const response = await getOrdersStatistics(params)

    statisticsData.value = response.data
    initCharts()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  getStatisticsData()
}

// 重置查询
const handleReset = () => {
  queryParams.startDate = ''
  queryParams.endDate = ''
  queryParams.type = 'day'
  handleQuery()
}

// 图表实例
let salesChart = null
let orderChart = null

// 初始化图表
const initCharts = () => {
  const timeline = statisticsData.value.timeline
  const dates = timeline.map((item) => item.date)
  const amounts = timeline.map((item) => item.amount)
  const orders = timeline.map((item) => item.orders)

  // 销售额趋势图
  if (!salesChart) {
    salesChart = echarts.init(document.getElementById('sales-chart'))
  }
  salesChart.setOption({
    title: {
      text: '销售额趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />销售额: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '销售额',
        data: amounts,
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  })

  // 订单数量趋势图
  if (!orderChart) {
    orderChart = echarts.init(document.getElementById('order-chart'))
  }
  orderChart.setOption({
    title: {
      text: '订单数量趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />订单数: {c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        data: orders,
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  })
}

// 处理窗口大小变化
const handleResize = () => {
  salesChart?.resize()
  orderChart?.resize()
}

// 组件挂载时初始化
onMounted(() => {
  getStatisticsData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  salesChart?.dispose()
  orderChart?.dispose()
})
</script>

<template>
  <div class="statistics-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8">
          <el-date-picker
            v-model="queryParams.startDate"
            type="date"
            placeholder="开始日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-date-picker
            v-model="queryParams.endDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-select
            v-model="queryParams.type"
            placeholder="统计类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-4">
        <el-col :span="24" style="text-align: right">
          <el-button
            type="primary"
            :icon="Search"
            @click="handleQuery"
            :loading="loading"
          >
            查询
          </el-button>
          <el-button :icon="RefreshRight" @click="handleReset">
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 统计数据卡片 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover">
          <el-statistic
            title="总订单数"
            :value="statisticsData?.totalOrders"
            :precision="0"
          >
            <template #prefix>
              <el-icon style="vertical-align: -0.125em">
                <Document />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover">
          <el-statistic
            title="总销售额"
            :value="statisticsData?.totalAmount"
            :precision="2"
          >
            <template #prefix>¥</template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8">
        <el-card shadow="hover">
          <el-statistic
            title="平均订单金额"
            :value="statisticsData?.avgOrderAmount"
            :precision="2"
          >
            <template #prefix>¥</template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :xs="24" :lg="12">
        <el-card>
          <div id="sales-chart" style="height: 400px" />
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card>
          <div id="order-chart" style="height: 400px" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.statistics-container {
  padding: 20px;
}

.mt-4 {
  margin-top: 1rem;
}

.search-card {
  margin-bottom: 1rem;
}

:deep(.el-card) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-card:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .statistics-container {
    padding: 10px;
  }

  .el-col {
    margin-bottom: 1rem;
  }
}

/* Chart container */
#sales-chart,
#order-chart {
  width: 100%;
  height: 400px;
}
</style>
